﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using AllInOne.PrintUtils;
using System.Threading;
using AllInOne.HDI.CRT_591_M001;
using AllInOne.Models;
using Newtonsoft.Json.Linq;
using AllInOne.Entity;
using System.Text.RegularExpressions;
using RestSharp;
using AllInOne.Classes;
using AllInOne.Pages;
using AllInOne.ModelDb;

namespace AllInOne.MainPages
{
    /// <summary>
    /// 测试前面的东西：
    /// DemoPrint.xaml 的交互逻辑
    /// </summary>
    public partial class DemoRFCardPage : Page
    {
        /// <summary>
        /// 串口操作句柄
        /// </summary>
        UInt32 Hdle = 0;

        private PrintUtil printUtil = new PrintUtil();
        private MainWindow parent;

        public DemoRFCardPage(MainWindow parent)
        {
            InitializeComponent();
            //initWindow();
            this.parent = parent;
        }
        public void initWindow()
        {
            System.Drawing.Image verifyImage = this.printUtil.GetLoginVerifyCode("10.231.3.1:9091");
            //this.showVerifyCode(verifyImage);
        }
        //数据绑定
        List<string> list = new List<string>();
        public void InitPage()
        {
            ////输入信息---证件打印时的号，
            //this.txtLsh.Text = "";

            //this.parent.OpenBarcode();
            //this.imgTitle.Source = new BitmapImage(new Uri(this.parent.businessInfo.getImgTitleUrl()));
            //this.parent.PlaySound(Properties.Resources.male_input_order, Properties.Resources.female_input_order);
            //MessageBox.Show("进入测试页面");

            //存身份证号加密码存储---
            //if (!)
            //{
            //    MessageBox.Show("数据保存--失败");
            //}
            //else
            //{
            //    MessageBox.Show("数据保存--成功");
            //}
            //();

            //加载收货单位
            List<ReceiverList> receiverList = ServiceWebApi.GetReceiverList();

            list.Clear();
            if (receiverList != null)
            {
                //也可以没有收货单位
                list.Add("无");
                for (int i = 0; i < receiverList.Count; i++)
                {
                    list.Add(receiverList[i].receiver);
                }
            }
            SenderName.ItemsSource = list;
        }


        #region 01发卡机等硬件通信测试

        private void btnConect_Click(object sender, RoutedEventArgs e)
        {

            Hdle = GrantCardClient.CommOpenWithBaut(txtPortCombo.Text, (uint)Convert.ToUInt32(txtBaudrate.Text.ToString()));
            if (Hdle != 0)
            {
                AppendText("串口打开成功");
                txtbShowTip.Text = "Comm. Port is Opened";
            }
            else
            {
                AppendText("串口打开失败");
                txtbShowTip.Text = "Open Comm. Port Error";
            }
        }



        /// <summary>
        /// 作者：YangZhike
        /// 创建日期：2022-04-26
        /// 描述：展示数据
        /// </summary>
        /// <param name="str">操作结果内容</param>
        private void AppendText(string str)
        {
            this.Dispatcher.Invoke(new Action(delegate
            {
                rTextBox.AppendText("\n" + str);
                rTextBox.ScrollToEnd();
            }));
        }

        private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            if (Hdle != 0)
            {
                int i = GrantCardClient.CommClose(Hdle);
                Hdle = 0;
                AppendText("关闭成功");
                txtbShowTip.Text = "Comm. Port is Closed";
            }
        }

        private void btnInit_Click(object sender, RoutedEventArgs e)
        {
            string msg;
            if (GrantCardClient.InitCard(Hdle, "00", out msg))
            {
                AppendText("初始化成功");
                txtbShowTip.Text = "初始化成功";
            }
            else
            {
                AppendText("初始化失败：" + msg);
                txtbShowTip.Text = "初始化失败：" + msg;
            }
        }

        private void btnMoveCardToFront1_Click(object sender, RoutedEventArgs e)
        {

        }

        private void btnMoveCardToRecycleBin_Click(object sender, RoutedEventArgs e)
        {
            string msg;
            if (GrantCardClient.MoveCardToRecycleBin(Hdle, "00", out msg))
            {

                AppendText("移卡到盒里成功");
                txtbShowTip.Text = "移卡到盒里成功";
            }
            else
            {
                AppendText("移卡到盒里失败：" + msg);
                txtbShowTip.Text = "移卡到盒里失败：" + msg;
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {

        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            string msg;
            if (GrantCardClient.AllCardIn(Hdle, "00", out msg))
            {

                AppendText("允许进卡成功");
                txtbShowTip.Text = "允许进卡成功";
            }
            else
            {
                AppendText("允许进卡失败：" + msg);
                txtbShowTip.Text = "允许进卡失败：" + msg;
            }
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            string msg;
            if (GrantCardClient.NoCardIn(Hdle, "00", out msg))
            {

                AppendText("禁止进卡成功");
                txtbShowTip.Text = "禁止进卡成功";
            }
            else
            {
                AppendText("禁止进卡失败：" + msg);
                txtbShowTip.Text = "禁止进卡失败：" + msg;
            }
        }

        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            string msg;
            string RFType;
            if (GrantCardClient.RFTestType(Hdle, "00", out RFType, out msg))
            {

                AppendText("获取RF卡成功：" + RFType);
                txtbShowTip.Text = "获取RF卡成功：" + RFType;
            }
            else
            {
                AppendText("获取RF卡失败：" + msg);
                txtbShowTip.Text = "获取RF卡失败：" + msg;
            }
        }
        private void Button_Click_4(object sender, RoutedEventArgs e)
        {
            string msg;
            string ICType;
            if (GrantCardClient.ICTestType(Hdle, "00", out ICType, out msg))
            {

                AppendText("获取RF卡成功：" + ICType);
                txtbShowTip.Text = "获取RF卡成功：" + ICType;
            }
            else
            {
                AppendText("获取RF卡失败：" + msg);
                txtbShowTip.Text = "获取RF卡失败：" + msg;
            }
        }

        private void Button_Click_5(object sender, RoutedEventArgs e)
        {
            string msg;
            string UID;
            if (GrantCardClient.MiCardActivate(Hdle, "00", out UID, out msg))
            {
                AppendText("读取卡号成功,卡号：" + UID);
                txtbShowTip.Text = "读取卡号成功,卡号：" + UID;
            }
            else
            {
                AppendText("读取卡号失败：" + msg);
                txtbShowTip.Text = "读取卡号失败：" + msg;
            }
        }

        private void Button_Click_6(object sender, RoutedEventArgs e)
        {
            string msg;
            if (GrantCardClient.MiCardDactivate(Hdle, "00", out msg))
            {
                AppendText("下电释放成功" + msg);
                txtbShowTip.Text = "下电释放成功" + msg;
            }
            else
            {
                AppendText("下电释放失败：" + msg);
                txtbShowTip.Text = "下电释放失败：" + msg;
            }
        }

        private void Button_Click_7(object sender, RoutedEventArgs e)
        {
            string msg;
            if (GrantCardClient.MoveCardToFront1(Hdle, "00", out msg))
            {

                AppendText("移卡到前端不持卡位成功");
                txtbShowTip.Text = "移卡到前端不持卡位成功";
            }
            else
            {
                AppendText("移卡到前端不持卡位失败：" + msg);
                txtbShowTip.Text = "移卡到前端不持卡位失败：" + msg;
            }
        }

        private void Button_Click_8(object sender, RoutedEventArgs e)
        {
            string msg;
            if (GrantCardClient.MoveCardToFront2(Hdle, "00", out msg))
            {

                AppendText("移卡到前端持卡位成功");
                txtbShowTip.Text = "移卡到前端持卡位成功";
            }
            else
            {
                AppendText("移卡到前端持卡位失败：" + msg);
                txtbShowTip.Text = "移卡到前端持卡位失败：" + msg;
            }
        }
        private void Button_Click_9(object sender, RoutedEventArgs e)
        {
            string msg;
            if (GrantCardClient.MoveCardToRF(Hdle, "00", out msg))
            {
                AppendText("移卡到RF位成功");
                txtbShowTip.Text = "移卡到RF位成功";
            }
            else
            {
                AppendText("移卡到RF位失败：" + msg);
                txtbShowTip.Text = "移卡到RF位失败：" + msg;
            }

        }
        private void Button_Click_10(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("暂不支持IC的移动");
        }

        private void Button_Click_20(object sender, RoutedEventArgs e)
        {
            VoiceHelper.Speak("您好,我是自助机");
            Thread.Sleep(5000);
            VoiceHelper.Speak("我是自助机");
        }

        #endregion


        #region 02基础信息录入测试
        private void SenderName_TextChanged(object sender, TextChangedEventArgs e)
        {
            //每次内容有变动，则进行下拉项展示
            SenderName.IsDropDownOpen = true;
            string input = SenderName.Text;
            if (!string.IsNullOrEmpty(input))
            {
                List<string> pList = list.FindAll(s => s.Contains(input));
                SenderName.ItemsSource = pList;
            }
            else
            {
                SenderName.ItemsSource = list;
            }
            //private void ComboBox_Prescription_TextChanged(object sender, RoutedEventArgs e)
            //{
            //    ComboBox_Prescription.IsDropDownOpen = true;
            //    string input = ComboBox_Prescription.Text;
            //    if (!string.IsNullOrEmpty(input))
            //    {
            //        Prescription pres = new Prescription();
            //        pres.PrescriptionShortCode = input;
            //        List<Prescription> pList = presDao.getPrescriptionListByShortCodeFuzzy(pres);
            //        ComboBox_Prescription.ItemsSource = pList;
            //    }
            //    else
            //    {
            //        List<Prescription> pList = presDao.getAll();
            //        ComboBox_Prescription.ItemsSource = pList;
            //    }
            //}


        }
        #endregion

        private void Btn_Back_Click(object sender, RoutedEventArgs e)
        {
            this.parent.ResetIndex();
        }

        /// <summary>
        /// 测试接口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_GetReg_Click(object sender, RoutedEventArgs e)
        {
            string guid = "660ad5f3-fb38-4340-9aff-1e976ec93565";
            string card = "888";
            T_RegisterInfo t_RegisterInfo = new T_RegisterInfo();
            t_RegisterInfo.Guid = guid;
            t_RegisterInfo.ICardNum = card;


            //JObject lsxx = ServiceWebApi.UpdataRegisterInfo(t_RegisterInfo);
            ////
            //if (lsxx != null)
            //{
            //    MessageBox.Show(lsxx.ToString());
            //}
        }

        private void Btn_TestICcard_Click(object sender, RoutedEventArgs e)
        {
            string CardUID = "";

            byte[] RxData = new byte[1024];
            RxData[3] = 4;
            RxData[4] = 0x9D;
            RxData[5] = 0x5D;
            RxData[6] = 0xE2;
            RxData[7] = 0x5D;
            //5DE25D9D 
            int n = 0;
            for (n = 0; n < RxData[3]; n++)
            {
                CardUID += RxData[n + 4].ToString("X2");
            }
            MessageBox.Show("原卡号：" + CardUID);
            CardUID = "";
            for (n = 0; n < RxData[3]; n++)
            {
                CardUID = RxData[n + 4].ToString("X2") + CardUID;
            }
            MessageBox.Show("新卡号：" + CardUID);
        }

        private void SenderName_KeyUp(object sender, KeyEventArgs e)
        {
            //if (e.key == key.enter)
            //{
            //    //你的逻辑
            //}
            //Dictionary<int, string> dicCustomVars = new Dictionary<int, string>();
            //foreach (CustomVars customVar in customVarsList)
            //{
            //    if (customVar.VarName.Contains(cbCustomVar.Text.Trim()) || customVar.VarCode.Contains(cbCustomVar.Text.Trim())
            //        || customVar.VarName.Contains(cbCustomVar.Text.Trim().ToLower()) || customVar.VarCode.Contains(cbCustomVar.Text.Trim().ToLower())
            //        || customVar.VarName.Contains(cbCustomVar.Text.Trim().ToUpper()) || customVar.VarCode.Contains(cbCustomVar.Text.Trim().ToUpper()))
            //    {
            //        dicCustomVars.Add(customVar.Id, customVar.VarName + "（" + customVar.VarCode + "）");
            //    }

            //}
            //this.cbCustomVar.ItemsSource = "";
            //cbCustomVar.ItemsSource = dicCustomVars;
            //this.cbCustomVar.SelectedIndex = -1;
            //cbCustomVar.IsDropDownOpen = true;

            //每次内容有变动，则进行下拉项展示
            string input = SenderName.Text;
            SenderName.ItemsSource = "";
            if (!string.IsNullOrEmpty(input))
            {
                List<string> pList = list.FindAll(s => s.Contains(input));
                SenderName.ItemsSource = pList;
            }
            //else
            //{
            //    SenderName.ItemsSource = list;
            //}
            this.SenderName.SelectedIndex = -1;
            SenderName.IsDropDownOpen = true;

            //List<string> mylist = new List<string>();
            //mylist = list.FindAll(delegate (string s) { return s.Contains(comboBox1.Text.Trim()); });
            //comboBox1.ItemsSource = mylist;
            //comboBox1.IsDropDownOpen = true;
        }

        private void SenderName_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void tb_Phone2_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            tb_Phone2.Text = ShowInPutNumberWin("人员手机", tb_Phone2.Text.Trim());
        }

        //当前的输入
        InPutNumberWin view;
        string currentInput = "";
        public string ShowInPutNumberWin(string textInput, string oldNumber)
        {
            //提取纯数字，该方式会将所有数字提取出来并拼接在一起，如："ABC#123@AS456测试"提取出来就是123456
            oldNumber = Regex.Replace(oldNumber, @"[^0-9]+", "");
            currentInput = textInput;
            view = null;
            //弹出页面
            view = new InPutNumberWin(currentInput, oldNumber);
            view.Owner = this.parent;
            view.ShowInTaskbar = false;
            view.WindowStartupLocation = WindowStartupLocation.Manual;
            view.Top = 400;
            view.Left = 380;
            if (view.ShowDialog() == true)
            {
                return view.newNumber;
            }
            else
            {
                return oldNumber;
            }
        }

        /// <summary>
        /// 根据卡号归还IC卡
        /// </summary>
        /// <param name="ICCardNum">卡号</param>
        public void BackICardByCardNum(string ICCardNum)
        {
            try
            {
                string msg = "";
                SimpleConsole.WriteInfo("还卡操作卡号" + ICCardNum, this);

                string url = ServiceWebApi.BASE_URL + "SSMachine/BackICardByCardNum";
                var client = new RestClient(url);
                var request = new RestRequest(Method.POST);
                //request.AddHeader("Accept", "*/*");//‘可省略
                request.AddParameter("CardNum", ICCardNum);
                var response = client.Execute(request);
                if (!string.IsNullOrEmpty(response.Content))
                {
                    BackInfo backInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<BackInfo>(response.Content);
                    if (backInfo.code == 200)//还卡，并将出门证打印出来
                    {
                        ExitViewModel exitViewModel = Newtonsoft.Json.JsonConvert.DeserializeObject<ExitViewModel>(backInfo.data.ToString());
                        string IdentityNum = exitViewModel.IdentityNum;
                        if (!string.IsNullOrEmpty(IdentityNum) && IdentityNum.Length == 18)
                        {
                            if (SystemParam.HiddenBirthdy)//处理是否隐藏生日
                            {
                                if (IdentityNum.Length == 18)
                                {
                                    //7-14是生日位
                                    string tempStr = IdentityNum.Substring(0, 10) + "****" + IdentityNum.Substring(14, 4);
                                    IdentityNum = tempStr;
                                }
                            }
                        }

                        //并将卡传到收卡箱中 "移卡到盒里成功"
                        if (GrantCardClient.MoveCardToRecycleBin(Hdle, "00", out msg))
                        {
                            //软件中的打印
                            List<string> InfoList = new List<string>();
                            InfoList.Add("出门证");
                            InfoList.Add(exitViewModel.Plate);
                            InfoList.Add(exitViewModel.RegName);
                            InfoList.Add(IdentityNum);
                            InfoList.Add(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                            Printer printer1 = new Printer
                            {
                                LoginID = 12,
                                InfoList = InfoList
                            };
                            //调用打印
                            printer1.Print();
                            LogHelper.WriteLog("打印出门证：完成！");
                            MessageBox.Show("还卡成功！");
                            return;
                        }
                        //还卡失败--将卡推送到最前面。
                        if (GrantCardClient.MoveCardToFront1(Hdle, "00", out msg))
                        {
                            MessageBox.Show("还卡失败，请取走你的卡片!");
                            return;
                        }
                    }
                    else if (backInfo.code == 201)
                    {
                        //将错误信息组合起来传到前台
                        switch (backInfo.data.ToString())
                        {
                            case "1"://"未识别的卡,不能进行还卡"
                            case "3"://"此卡已经完成称重,可以还卡,收回到卡槽,但更新数据库卡注册信息失败";
                            case "4"://"此卡未完成称重,不能还卡,卡重新从卡槽吐出";
                                if (GrantCardClient.MoveCardToFront1(Hdle, "00", out msg))
                                {
                                    MessageBox.Show($"还卡失败,{ backInfo.message} 请取走你的卡片!");
                                }
                                break;
                            case "5"://此卡没有过车记录,直接还卡,不打印出门证
                            case "6"://卡信息是厂内流转货物,直接还卡,不打印出门证
                            case "9"://此卡没有过车记录,直接还卡,不打印出门证
                            case "10"://此卡没有过车记录,直接还卡,不打印出门证
                                if (GrantCardClient.MoveCardToRecycleBin(Hdle, "00", out msg))
                                {
                                    MessageBox.Show("还卡成功!");
                                    this.parent.ResetIndex();
                                    return;
                                }
                                else
                                {
                                    //卡推送卡机失败，则吐出来
                                    if (GrantCardClient.MoveCardToFront1(Hdle, "00", out msg))
                                    {
                                        MessageBox.Show($"还卡失败,移动回收盒失败,请取走你的卡片!");
                                    }
                                }
                                break;
                            //case "7"://此卡已经完成称重,可以还卡
                            //break;
                            case "8":
                                if (GrantCardClient.MoveCardToFront1(Hdle, "00", out msg))
                                {
                                    MessageBox.Show($"还卡失败,{ backInfo.message} 请取走你的卡片!");
                                    return;
                                }
                                break;
                            default:
                                break;
                        }
                    }
                }
                else
                {
                    MessageBox.Show("连接服务器失败！");
                    //还卡失败--将卡推送到最前面。
                    if (GrantCardClient.MoveCardToFront1(Hdle, "00", out msg))
                    {
                        MessageBox.Show("还卡失败，请取走你的卡片!");
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                SimpleConsole.WriteError("还卡失败出错" + ex.ToString(), null);
            }
            this.parent.ResetIndex();
        }

        private void Btn2_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(txtICCardNum.Text.ToString()))
            {
                MessageBox.Show("请输入要还卡的卡号");
                return;
            }
            BackICardByCardNum(txtICCardNum.Text.ToString());
        }

        private void Btn3_Click(object sender, RoutedEventArgs e)
        {
            this.parent.Confirm("提示语", "提示内容", null, null);
        }

        private void BtnSM2_Test_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                WinTest_SM2 win = new WinTest_SM2();
                win.Owner = this.parent;
                win.ShowInTaskbar = false;
                win.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                //view.Top = 400;
                //view.Left = 380;
                if (win.ShowDialog() == true)
                {
                    //return view.newNumber;
                }
                else
                {
                    //return oldNumber;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void Btn2_Test_Click(object sender, RoutedEventArgs e)
        {
            //this.parent.Alert("提示", "  未读取到二维码信息。", new OkDelegate(delegate ()
            //{
            //    return;
            //}));

            this.parent.Alert("提示", "操作超时。", delegate () {
                //this.PrintVoidLogo();
                //this.SendMsgToScm(ComCommand.PRINT_DRIVING_LICENSE_FUJITSU_PRINT_FAILED);
                //this.ResetIndex();
            });

        }

        private void Btn3_Test_Click(object sender, RoutedEventArgs e)
        {
            this.parent.Confirm("提示", "取消申请?",
                delegate () {
                    //this.wbTable.Visibility = Visibility.Visible;
                    this.parent.ResetIndex();
                },
                delegate () {
                    //this.wbTable.Visibility = Visibility.Visible;

                });
        }

        private void Btn4_Test_Click(object sender, RoutedEventArgs e)
        {
            this.parent.demoPrintLicenceFront();

        }
        //PlateGoodsListPage view1;
        private void Btn5_Test_Click(object sender, RoutedEventArgs e)
        {
            //弹出页面
            PlateGoodsListPage view1 = new PlateGoodsListPage(this.parent);
            view1.Owner = this.parent;
            view1.ShowInTaskbar = false;
            List<VerifyPlateList> tempList = new List<VerifyPlateList>();
            VerifyPlateList temp = new VerifyPlateList();
            temp.Id = 1;
            temp.GoodsName = "铁粉";
            temp.Value1 = "2";
            temp.Value2 = "发货单位1";
            temp.Value3 = "收货单位1";
            tempList.Add(temp);
            view1.InitPage(tempList);
            view1.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            //view1.Show();
            if (view1.ShowDialog() == true)
            {
                MessageBox.Show("true");
            }
            else
            {
                MessageBox.Show("false");
            }
            ////view1.Top = 400;
            ////view1.Left = 380;
            //if (view1.ShowDialog() == true)
            //{
            //    //view1.ThisRecord;
            //    //return view.ThisRecord;
            //}
            //else
            //{
            //    //return oldNumber;
            //}
        }
    }
}
